package org.flown.shop.service;


import org.flown.shop.dao.GoodsDAO;
import org.flown.shop.dto.GoodsDTO;
import org.flown.shop.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;


@Service
public class GoodsService extends BaseService<Goods>
{
    @Autowired
    public GoodsService(GoodsDAO dao_goods) {super(dao_goods);}


    private Goods getGoodsByID(int id) {return this.selectByID(id);}
    public GoodsDTO getGoodsDTOByID(int id) {return new GoodsDTO(this.selectByID(id));}


    @Transactional
    public int insertGoods(Goods goods) {
        int result = this.insert(goods);
        if (result == 0)
            return 0;
        try {goods.savePictures();}
        catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);}
        return result;
    }

    @Transactional
    public boolean updateGoodsByID(Goods original_goods) {
        if (!this.updateByID(original_goods))
            return false;
        try {original_goods.savePictures();}
        catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);}
        return true;
    }

    public int deleteGoodsByID(int id) {
        Goods goods = this.getGoodsByID(id);
        int result = this.deleteByID(id);
        if (result == 0)
            return 0;
        File file = new File(goods.getDirectoryRealPath());
        file.delete();
        return result;
    }



}




